import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useAccount as useAccountStore } from '@/store/modules/account';
import { useUniqueStr } from '@/composables/useUniqueStr';
import type { CachedAccountInfo } from '@/types/account';

/**
 * 账户信息管理的 Composable 函数
 */
export function useAccount() {
  const accountStore = useAccountStore();
  const { uniqueStr } = useUniqueStr();
  
  // 定时器引用
  const checkTimer = ref<NodeJS.Timeout | null>(null);

  // 计算属性
  const accountInfo = computed(() => accountStore.getAccountInfo);
  const loading = computed(() => accountStore.isLoading);
  const error = computed(() => accountStore.getError);
  const isCacheExpired = computed(() => accountStore.isCacheExpired);
  const cacheRemainingTime = computed(() => accountStore.getCacheRemainingTime);

  // 获取账户信息
  const fetchAccountInfo = async (forceRefresh = false): Promise<CachedAccountInfo | null> => {
    if (!uniqueStr.value) {
      console.warn('uniqueStr 为空，无法获取账户信息');
      return null;
    }
    return await accountStore.getAccountInfoWithCache(uniqueStr.value, forceRefresh);
  };

  // 刷新账户信息
  const refreshAccountInfo = async (): Promise<CachedAccountInfo | null> => {
    return await fetchAccountInfo(true);
  };

  // 启动定时检查缓存过期
  const startCacheCheck = () => {
    if (checkTimer.value) {
      clearInterval(checkTimer.value);
    }

    // 每秒检查一次缓存状态
    checkTimer.value = setInterval(async () => {
      if (uniqueStr.value && accountStore.isCacheExpired && accountStore.accountInfo) {
        console.log('账户信息缓存已过期，自动刷新...');
        await fetchAccountInfo(true);
      }
    }, 1000);
  };

  // 停止定时检查
  const stopCacheCheck = () => {
    if (checkTimer.value) {
      clearInterval(checkTimer.value);
      checkTimer.value = null;
    }
  };

  // 初始化账户信息
  const initAccountInfo = async () => {
    if (uniqueStr.value) {
      await fetchAccountInfo();
      startCacheCheck();
    }
  };

  // 清除账户信息
  const clearAccountInfo = () => {
    accountStore.clearAccountInfo();
    stopCacheCheck();
  };

  // 组件挂载时初始化
  onMounted(() => {
    initAccountInfo();
  });

  // 组件卸载时清理定时器
  onUnmounted(() => {
    stopCacheCheck();
  });

  return {
    // 状态
    accountInfo,
    loading,
    error,
    isCacheExpired,
    cacheRemainingTime,
    
    // 方法
    fetchAccountInfo,
    refreshAccountInfo,
    initAccountInfo,
    clearAccountInfo,
    startCacheCheck,
    stopCacheCheck,
  };
}